<!--
/**
@template: 贵州见证私有组件
评审角色: 添加评审时间功能/暂停时间补丁
弹框+按钮
@author: ChaoPengWang(wangcp-a@glodon.com)
@update: 2022/4/16 9:36 PM
-->

<template>
  <div class="add-revive">
    <el-button
      v-if="isTask"
      size="default"
      icon="icon-time"
      @click="setShowReviewTimeDialog(true)">
      见证时间
    </el-button>

    <el-button
      v-else
      size="default"
      type="text"
      @click="setShowReviewTimeDialog(true)">
      见证时间
    </el-button>

    <el-dialog title="评审时间" :visible.sync="showReviewTimeDialog" width="700px">
      <div class="add-revive-top" v-if="isTask">
        <el-button type="primary" size="default" @click="addPauseAndRestoreTime"> 新增暂停</el-button>
      </div>
      <el-table :data="stopInfoList" class="add-revive-table">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column label="暂停时间" align="center">
          <!--          witnessStopTime-->
          <template slot-scope="{ row: { isEditor }, $index }">
            <div class="add-revive-table-td">
              <el-date-picker
                :class="{
                  'add-revive-table-border': !isEditor
                }"
                :disabled="!isTask"
                style="margin: auto; width: 150px"
                :readonly="!isEditor"
                @change="validationPauseAndRestoreTime($index, 'START')"
                v-model="stopInfoList[$index].witnessStopTime"
                size="mini"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="恢复时间" align="center">
          <template slot-scope="{ row: { isEditor }, $index }">
            <div class="add-revive-table-td">
              <el-date-picker
                :disabled="!isTask"
                :class="{
                  'add-revive-table-border': !isEditor
                }"
                style="margin: auto; width: 150px"
                :readonly="!isEditor"
                v-model="stopInfoList[$index].witnessRecoveryTime"
                size="mini"
                type="datetime"
                @change="validationPauseAndRestoreTime($index, 'END')"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </div>
          </template>
          <template />
        </el-table-column>
        <el-table-column prop="duration" label="停/复时长" align="center" />
        <el-table-column label="操作" width="100" align="center" v-if="isTask">
          <template slot-scope="{ row: { isEditor, witnessRecoveryTime, stopId }, $index }">
            <el-button
              type="text"
              :style="{
                color: isEditor ? '#57b21c' : ''
              }"
              size="default"
              @click="setPauseAndRestoreTimeEditorByIndex($index, isEditor)"
            >
              {{ isEditor ? "确定" : "编辑" }}
            </el-button>
            <el-button type="text" size="default" @click="deletePauseAndRestoreTime($index, stopId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-row>
        <el-col :span="12">
          <div class="add-revive-bottom">
            <div>评审开始时间:</div>
            <el-date-picker
              v-model="evaluationStartTime"
              type="datetime"
              @change="validationStateAndEndTime('START')"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="add-revive-bottom">
            <div>评审结束时间:</div>
            <el-date-picker
              @change="validationStateAndEndTime('END')"
              v-model="evaluationEndTime"
              type="datetime"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </div>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReviewTime">确定</el-button>
        <el-button @click="setShowReviewTimeDialog(false)">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import moment from "moment";
  import { formatAll, formatMs, genTime, validationTime } from "./utils";
  import { GZAPI_EvaluationTime } from "../api";

  export default {
    name: "gzAddReviewTime",
    data: () => ({
      //评审开始时间
      evaluationStartTime: null,
      //评审结束时间
      evaluationEndTime: null,
      //评审暂停时间列表
      stopInfoList: [],
      // 是否显示弹框
      showReviewTimeDialog: false
    }),
    props:{
      id: {
        type: String,
        required: true
      },
      type: {
        type: String,
        default: 'TASK'
      }
    },
    created() {
      this.changeDate = {
        lodEvaluationStartTime: "",
        lodEvaluationEndTime: "",
        lodStopInfoMap: new Map()
      };
    },

    computed:{
      isTask (){
        return this.type === 'TASK'
      }
    },
    methods: {
      //控制见证时间弹框的显示/隐藏
      setShowReviewTimeDialog(boo) {
        if (boo) {
          this.changeDate.lodEvaluationStartTime = "";
          this.changeDate.lodEvaluationEndTime = "";
          this.changeDate.lodStopInfoMap.clear();
          this.getReviewTime();
        }
        this.showReviewTimeDialog = boo;
      },

      //新增评审时间 暂停/恢复数据
      addPauseAndRestoreTime() {
        this.setPauseAndRestoreTimeEditorByIndex(0, true);
        this.stopInfoList.push({
          witnessStopTime: null,
          witnessRecoveryTime: null,
          duration: "",
          isEditor: true
        });
      },

      //暂停/恢复时间进入编辑状态
      setPauseAndRestoreTimeEditorByIndex(index, isEditor) {
        const { stopInfoList } = this;
        this.stopInfoList = stopInfoList.map((item, i) => {
          item.isEditor = isEditor ? false : index === i;
          return item;
        });
      },

      //暂停/恢复时间校验
      validationPauseAndRestoreTime(index, type) {
        const { witnessStopTime, witnessRecoveryTime } = this.stopInfoList[index];
        const result = validationTime(witnessStopTime, witnessRecoveryTime, type);

        switch (result) {
          case "START_ERROR":
            this.stopInfoList[index].witnessStopTime = "";

            this.$message({
              type: "warning",
              message: `评审开始时间不能小于等于评审结束时间`,
              single: true
            });
            break;
          case "END_ERROR":
            this.stopInfoList[index].witnessRecoveryTime = "";
            this.$message({
              type: "warning",
              message: `评审结束时间不能小于等于评审开始时间`,
              single: true
            });
            break;
          case "OK":
            if (witnessRecoveryTime && witnessStopTime) {
              this.stopInfoList[index].duration = genTime(formatMs(witnessStopTime), formatMs(witnessRecoveryTime));
            }
            break;
        }
      },

      //开始/结束时间校验
      validationStateAndEndTime(type) {
        const { evaluationStartTime, evaluationEndTime } = this;
        const result = validationTime(evaluationStartTime, evaluationEndTime, type);
        switch (result) {
          case "START_ERROR":
            this.evaluationStartTime = "";

            this.$message({
              type: "warning",
              message: `评审开始时间不能小于等于评审结束时间`,
              single: true
            });
            break;
          case "END_ERROR":
            this.evaluationEndTime = "";
            this.$message({
              type: "warning",
              message: `评审结束时间不能小于等于评审开始时间`,
              single: true
            });
            break;
        }
      },

      // 提交修改
      submitReviewTime() {
        let { lodEvaluationEndTime, lodEvaluationStartTime, lodStopInfoMap } = this.changeDate;
        const { evaluationEndTime, evaluationStartTime, stopInfoList, isTask } = this;
        const updateEvaluationTimeData = {};

        if (evaluationEndTime !== lodEvaluationEndTime || evaluationStartTime !== lodEvaluationStartTime) {
          updateEvaluationTimeData.evaluationEndTime = formatAll(evaluationEndTime);
          updateEvaluationTimeData.evaluationStartTime = formatAll(evaluationStartTime);
        }

        const addOrUpdateStopInfoData = [];

        stopInfoList.forEach((item) => {
          const mapItem = lodStopInfoMap.get(item.stopId);
          if (
            mapItem &&
            mapItem.witnessStopTime === item.witnessStopTime &&
            mapItem.witnessRecoveryTime === item.witnessRecoveryTime
          ) {
            return;
          }
          const dataItem = {
            witnessStopTime: formatAll(item.witnessStopTime),
            witnessRecoveryTime: formatAll(item.witnessRecoveryTime)
          };
          item.stopId && (dataItem.stopId = item.stopId);
          addOrUpdateStopInfoData.push(dataItem);
        });

        const promiseList = [];

        //提交评审开始/结束时间
        if (Object.keys(updateEvaluationTimeData).length > 0) {
          let url;
          const param = {};
          if (isTask){
            param.witnessSubTaskId = this.id;
            url = 'updateEvaluationTime';
          } else {
            url = 'updateObjectEvaluationTime';
            param.projectId = this.id
          }

          promiseList.push(
            GZAPI_EvaluationTime[url]({
              ...updateEvaluationTimeData,
              ...param
            })
          );
        }

        // 修改暂停/恢复时间
        if (addOrUpdateStopInfoData.length > 0 && isTask) {
          promiseList.push(
            GZAPI_EvaluationTime.addOrUpdateStopInfo({
              stopInfoList: addOrUpdateStopInfoData,
              witnessSubTaskId: this.id
            })
          );
        }

        if (promiseList.length) {
          Promise.all(promiseList)
            .then(([data1, data2]) => {
              if (
                (promiseList.length === 1 && data1.success) ||
                (promiseList.length === 2 && data1.success && data2.success)
              ) {
                this.$message({
                  type: "success",
                  message: "修改成功",
                  single: true
                });
                this.setShowReviewTimeDialog(false);
              } else {
                this.$message({
                  type: "error",
                  message: `${data1.message} ${data2 ? data2.message : ""}` || "获取数据失败，请稍后再试",
                  single: true
                });
              }
            })
            .catch((e) => console.error(e));
        } else {
          this.setShowReviewTimeDialog(false);
        }
      },

      //删除暂停时间
      async deletePauseAndRestoreTime(index, stopId) {
        try {
          if (stopId) {
            const { code, message } = await GZAPI_EvaluationTime.deleteStopInfo({
              stopId
            });
            if (code === 0) {
              this.$message({
                type: "success",
                message: "删除暂停时间/恢复时间成功",
                single: true
              });
            } else {
              this.$message({
                type: "error",
                message: message || "获取数据失败，请稍后再试",
                single: true
              });
            }
          }
          this.stopInfoList.splice(index, 1);
        } catch (e) {
          console.error(e);
        }
      },

      //获取暂停时间信息
      async getReviewTime() {
        try {
          const { changeDate, isTask, id } = this;

          const param = {};
          let url;

          if (isTask) {
            param.witnessSubTaskId = id;
            url = 'getEvaluationTimeAndStopInfo';
          } else {
            param.projectId = id;
            url = 'getProjectEvaluationTimeAndStopInfo';
          }

          const { message, code, data } = await GZAPI_EvaluationTime[url](param);
          if (code === 0) {
            const { evaluationEndTime, evaluationStartTime, stopInfoList } = data;
            this.evaluationEndTime = changeDate.lodEvaluationEndTime = evaluationEndTime;
            this.evaluationStartTime = changeDate.lodEvaluationStartTime = evaluationStartTime;
            this.stopInfoList = stopInfoList.map((item) => {
              let duration = "";
              const { witnessStopTime, witnessRecoveryTime } = item;
              const st = witnessStopTime && moment(witnessStopTime).format("x");
              const et = witnessRecoveryTime && moment(witnessRecoveryTime).format("x");
              if (witnessRecoveryTime && witnessStopTime) {
                duration = genTime(st - 0, et - 0);
              }
              return {
                ...item,
                duration: duration,
                isEditor: false
              };
            });

            stopInfoList.forEach(({ stopId, witnessStopTime, witnessRecoveryTime }) => {
              changeDate.lodStopInfoMap.set(stopId, {
                witnessStopTime,
                witnessRecoveryTime
              });
            });
          } else {
            this.$message({
              type: "error",
              message: message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (e) {
          console.error(e);
        }
      }
    }
  };
</script>

<style scoped lang="scss">
  .add-revive {
    display: inline-block;
    margin-left: 10px;

    .add-revive-top {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 10px;
    }

    .add-revive-table {
      margin-bottom: 20px;

      .add-revive-table-td {
        display: flex;
        align-items: center;
        height: 35px;

        .add-revive-table-border {
          ::v-deep .el-input__inner {
            border-color: transparent;
          }
        }
      }
    }

    .add-revive-bottom {
      display: flex;
      align-items: center;

      & > div:first-child {
        margin-right: 10px;
      }
    }
  }

  ::v-deep .el-icon-time {
    display: none;
  }

  ::v-deep .el-input--suffix .el-input__inner {
    padding-right: 0;
  }

  ::v-deep .el-table__body,
  .el-table__footer,
  .el-table__header {
    table-layout: auto;
  }

  ::v-deep .el-dialog__body {
    padding: 10px 20px;
  }
</style>
